<template>
  <el-drawer v-model="drawerVisible" :z-index="1000" :destroy-on-close="true" size="1000px" :title="`${drawerProps.title}`">
    <div class="employeeDrawer">
      <div class="tree" v-loading="loading1">
        <ZTree
          :id="treeId"
          :zNodes="drawerProps.zNodes"
          :checkNodeId="drawerProps.row!.dptid"
          @click-dom="zTreeOnClick"
          v-if="isShow"
        />
      </div>
      <el-form
        class="employeeForm"
        ref="EmployeeFormRef"
        label-width="100px"
        label-suffix=" :"
        :rules="rules"
        :disabled="drawerProps.isView"
        :model="drawerProps.row"
        :hide-required-asterisk="drawerProps.isView"
      >
        <div class="userInfo" v-if="drawerProps.title === '编辑'">
          <div class="userInfo__name">{{ userName }}</div>
          <el-image class="userInfo__avatar" :src="avatar" :preview-src-list="[avatar]"></el-image>
        </div>
        <el-form-item label="编码" prop="empcode">
          <el-input
            v-model="drawerProps.row!.empcode"
            placeholder="请填写编码"
            :readonly="drawerProps.title === '编辑'"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="姓名" prop="empname">
          <el-input v-model="drawerProps.row!.empname" placeholder="请填写姓名" clearable></el-input>
        </el-form-item>
        <!-- <el-form-item class="password" label="密码" prop="password" v-if="drawerProps.title === '新增'">
          <el-input type="password" v-model="drawerProps.row!.password" placeholder="请输入密码" autocomplete="new-password">
            <template #prefix>
              <el-icon class="el-input__icon"><lock /></el-icon>
            </template>
          </el-input>
        </el-form-item> -->
        <el-form-item label="性别">
          <el-select v-model="drawerProps.row!.sex" placeholder="请选择性别">
            <el-option v-for="item in genderType" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="持卡类别">
          <el-select v-model="drawerProps.row!.ctcode" placeholder="请选择持卡类别">
            <el-option v-for="item in ecardTypes" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="drawerProps.row!.dptname" placeholder="请填写部门" clearable readonly></el-input>
        </el-form-item>
        <el-form-item label="职务">
          <el-input v-model="drawerProps.row!.job" placeholder="请填写职务" clearable></el-input>
        </el-form-item>
        <!-- <el-form-item label="电话[手机]">
          <el-input v-model="drawerProps.row!.phone" placeholder="请填写电话[手机]" clearable></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="证件号码">
          <el-input v-model="drawerProps.row!.cyd" placeholder="请填写职务" clearable></el-input>
        </el-form-item> -->
        <el-form-item label="卡有效期">
          <el-date-picker v-model="drawerProps.row!.cardvalid" type="datetime" placeholder="请填写卡有效期" clearable />
        </el-form-item>
        <el-form-item label="门禁有效期">
          <el-date-picker v-model="drawerProps.row!.rulevalid" type="datetime" placeholder="请填写门禁有效期" clearable />
        </el-form-item>
        <el-form-item label="民族">
          <el-input v-model="drawerProps.row!.nation" placeholder="请填写民族" clearable></el-input>
        </el-form-item>
        <el-form-item label="文化程度">
          <el-input v-model="drawerProps.row!.highestDegree" placeholder="请填写民族" clearable></el-input>
        </el-form-item>
        <el-form-item label="政治面貌">
          <el-input v-model="drawerProps.row!.politicalStatus" placeholder="请填写政治面貌" clearable></el-input>
        </el-form-item>
        <el-form-item label="籍贯">
          <el-input v-model="drawerProps.row!.placeOfBirth" placeholder="请填写籍贯" clearable></el-input>
        </el-form-item>
        <!-- <el-form-item label="出生日期">
          <el-date-picker
            v-model="drawerProps.row!.birthday"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD"
            type="date"
            placeholder="请选择出生日期"
          />
        </el-form-item> -->
        <el-form-item label="工作证号">
          <el-input v-model="drawerProps.row!.workCardNumber" placeholder="请填写工作证号" clearable></el-input>
        </el-form-item>
        <!-- <el-form-item label="EMail">
          <el-input v-model="drawerProps.row!.email" placeholder="请填写EMail" clearable></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="办公电话">
          <el-input v-model="drawerProps.row!.uphone" placeholder="请填写办公电话" clearable></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="户口所在地">
          <el-input v-model="drawerProps.row!.hukouAddress" placeholder="请填写户口所在地" clearable></el-input>
        </el-form-item>
        <el-form-item label="办公地址">
          <el-input v-model="drawerProps.row!.officeAddress" placeholder="请填写办公地址" clearable></el-input>
        </el-form-item>
        <el-form-item label="家庭住址">
          <el-input v-model="drawerProps.row!.homeaddress" placeholder="请填写家庭住址" clearable></el-input>
        </el-form-item> -->
        <el-form-item label="备注">
          <el-input v-model="drawerProps.row!.comment" placeholder="请填写备注" clearable></el-input>
        </el-form-item>
        <el-form-item label="照片" prop="photoContent" v-if="drawerProps.title === '编辑'">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-preview="handlePictureCardPreview"
            :http-request="_uploadFile"
          >
            <img v-if="avatar" :src="avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="_colse">取消</el-button>
      <el-button type="primary" :loading="loading" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="EmployeeDrawer">
/* eslint-disable */
// @ts-nocheck
import { ref, reactive, watch } from "vue";
import { ElMessage, FormInstance, UploadProps, UploadRequestOptions } from "element-plus";
import { VITE_API_URL } from "@/config";
import { genderType } from "@/utils/serviceDict";
import { convertImageToBase64, getAssetsFile } from "@/utils";
import dayjs from "dayjs";
import ZTree from "@/components/ZTree/index.vue";
import { uploadPhoto } from "@/api/modules/cardIssuingCenter/employeeManage";
import JSEncrypt from "jsencrypt";

let timer = null;

const treeId = ref("tree1");
const isShow = ref(false);
const rules = reactive({
  empcode: [{ required: true, trigger: "blur", message: "请填写编码" }],
  empname: [{ required: true, trigger: "blur", message: "请填写姓名" }]
  // password: [
  //   { required: true, message: "请输入密码", trigger: "blur" },
  //   {
  //     //插入正则验证：大小写、数字、至少6位、不常用字符
  //     pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()\-_=+{};:,<.>])[a-zA-Z][a-zA-Z0-9!@#$%^&*()\-_=+{};:,<.>]{5,17}$/,
  //     message: "密码6-18位(以字母开头，同时包含大写字母、小写字母、数字以及?=.*[!@#$%^&*()\-_=+{};:,<.>]特殊字符)",
  //     trigger: "blur"
  //   }
  // ]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: { [key: string]: any };
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  resetTableList?: () => void;
  ecardTypes: { [key: string]: any }[];
  zNodes: { [key: string]: any }[];
}

const loading = ref(false);
const loading1 = ref(false);
const avatar: any = ref("");
const userName = ref("");
const ecardTypes: any = ref([]);
const drawerVisible = ref(false);

const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {},
  ecardTypes: [],
  zNodes: []
});

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;

  try {
    const validDate = new Date().setFullYear(new Date().getFullYear() + 20);
    ecardTypes.value = drawerProps.value.ecardTypes;
    isShow.value = false;
    loading1.value = true;

    timer = setTimeout(() => {
      loading1.value = false;
      isShow.value = true;
    }, 2000);

    if (drawerProps.value.title === "新增") {
      avatar.value = getAssetsFile("images/user.gif");
      drawerProps.value.row.sex = genderType[0].value;
      if (ecardTypes.value.length) drawerProps.value.row.ctcode = ecardTypes.value[0].key;
      // drawerProps.value.row.birthday = dayjs(new Date()).format("YYYY-MM-DD");
      drawerProps.value.row!.cardvalid = dayjs(validDate).format("YYYY-MM-DD") + " 23:59:59";
      drawerProps.value.row!.rulevalid = dayjs(validDate).format("YYYY-MM-DD") + " 23:59:59";
    } else {
      userName.value = drawerProps.value.row.empname;
      avatar.value = getAssetsFile("images/user.gif");
      convertImageToBase64(
        `${VITE_API_URL}/employee/photo/download?empid=${drawerProps.value.row.empid}`,
        (base64Value: string) => {
          if (base64Value && base64Value !== "data:") avatar.value = base64Value;
        }
      );
    }
  } catch (error) {
    console.log(error);
  }
};

// 提交数据（新增/编辑）
const EmployeeFormRef = ref<FormInstance>();
/**
 * 关闭弹窗
 */
const _colse = () => {
  drawerVisible.value = false;
  EmployeeFormRef.value && EmployeeFormRef.value.resetFields();
};

/**
 * 文件上传
 */
const _uploadFile = (uploadFileOpts: UploadRequestOptions) => {
  return new Promise<void>(async resolve => {
    const file = uploadFileOpts!.file;
    const site = file.name.lastIndexOf("\.");

    const fileSuffix = file.name.substring(site + 1, file.name.length);

    const imgTypelist = ["png", "jpg", "jpeg", "gif"];
    if (!imgTypelist.includes(fileSuffix)) {
      ElMessage.error("文件类型不匹配或不支持该种类型文件");
      return false;
    }
    await uploadPhoto({ empid: drawerProps.value.row.empid, photo: file });
    filetoBase64(file as File).then(async (base64Value: any) => {
      if (base64Value.indexOf("base64,") != -1) {
        avatar.value = base64Value;
      }
    });
    resolve();
  });
};

/**
 * 点击树节点
 */
const zTreeOnClick = ({ treeNode }) => {
  drawerProps.value.row.dptid = treeNode.id;
  drawerProps.value.row.dptname = treeNode.name;
};

/**
 * 提交信息
 */
const handleSubmit = () => {
  EmployeeFormRef.value!.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    // const encryptor = new JSEncrypt();
    // if (drawerProps.value.row!.birthday)
    //   drawerProps.value.row!.birthday = dayjs(drawerProps.value.row!.birthday).format("YYYY-MM-DD HH:mm:ss");
    const params = drawerProps.value.row;
    // let password;
    // encryptor.setPublicKey(import.meta.env.VITE_PUBLIC_kEY);
    // if (drawerProps.value.title === "新增") {
    //   password = encryptor.encrypt(drawerProps.value.row!.password) as string;
    //   params.password = password;
    // }

    try {
      await drawerProps.value.api!({
        ...params
      });
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.title === "新增" ? drawerProps.value.resetTableList!() : drawerProps.value.getTableList!();
      drawerVisible.value = false;
      loading.value = false;
    } catch (error) {
      loading.value = false;
      console.log(error);
    }
  });
};

/**
 * 预览图片
 */
const handlePictureCardPreview: UploadProps["onPreview"] = uploadFile => {
  console.log(uploadFile);
  // dialogImageUrl.value = [uploadFile.url!];
  // dialogVisible.value = true;
};
const filetoBase64 = (file: File) => {
  let reader = new FileReader(); //实例化文件读取对象
  reader.readAsDataURL(file); //将文件读取为 DataURL,也就是base64编码
  return new Promise(reslove => {
    reader.onload = e => {
      //文件读取成功完成时触发
      if (e.target) {
        let dataURL = e.target.result; //获得文件读取成功后的DataURL,也就是base64编码
        reslove(dataURL);
      }
    };
  });
};

watch(
  () => drawerVisible.value,
  nV => {
    !nV && clearTimeout(timer);
  }
);
defineExpose({
  acceptParams
});
</script>
<style lang="scss" scoped>
.employeeDrawer {
  display: flex;
  height: 100%;
  padding: 0 20px;
  .tree {
    width: 320px;
    height: 100%;
    .ztree {
      height: 100%;
      overflow-y: auto;
    }
  }
  .employeeForm {
    flex: 1;
    padding: 10px 20px 0;
    overflow-y: auto;
  }
}
.userInfo {
  display: flex;
  align-items: center;
  padding: 10px 30px 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #eeeeee;
  .userInfo__avatar {
    width: 90px;
    height: 90px;
    margin-right: 10px;
    margin-bottom: 18px;
    background: #eeeeee;
    border: 1px solid #eeeeee;
    border-radius: 50%;
  }
  .userInfo__name {
    margin-right: 10px;
  }
}
</style>
<style scoped>
.avatar-uploader .avatar {
  display: block;
  width: 178px;
  height: 178px;
}
</style>

<style>
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
.employeeForm .password {
  margin-bottom: 30px;
}
</style>
